package com.yehun.config;

import com.yehun.enums.BaseEnum;
import com.yehun.utils.Constant;
import com.yehun.utils.EnumUtils;
import com.yehun.utils.ParseUtils;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;

@SuppressWarnings("unchecked")
public final class StringToEnumConverter implements ConverterFactory<String, BaseEnum> {

    public <T extends BaseEnum> Converter<String, T> getConverter(Class<T> targetType) {
        return new StringToEnum(targetType);
    }

    private class StringToEnum<T extends BaseEnum> implements Converter<String, T> {

        private final Class<T> enumType;

        public StringToEnum(Class<T> enumType) {
            this.enumType = enumType;
        }

        public T convert(String source) {
            if (source.length() == 0) {
                return null;
            }
            int value = ParseUtils.parseInt(source.trim(), Constant.Default.ValueInt);
            //return (T) Enum.valueOf(this.enumType, source.trim());
            return EnumUtils.getEnum(this.enumType, value);
        }
    }

}